<template>
  <div class="app-container">
    <div class="content-container">
      <!-- 顶部导航和标题区域 -->
      <div class="detail-header">
        <div class="detail-breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/knowledge/dataset' }"
              >知识库</el-breadcrumb-item
            >
            <el-breadcrumb-item>数据集</el-breadcrumb-item>
            <el-breadcrumb-item>{{ dataset_name }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>

      <!-- 数据集标题和提示 -->
      <div class="dataset-title-area">
        <h2>数据集</h2>
        <div class="dataset-tip">
          <el-icon><Warning /></el-icon>
          <span>解析成功后才能问答。</span>
        </div>
      </div>

      <!-- 功能区域 -->
      <div class="function-area">
        <el-dropdown trigger="click" class="batch-dropdown">
          <el-button :disabled="selectedRows.length == 0">
            批量 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- <el-dropdown-item @click="handleBatchEnable(true)">
                <el-icon class="batch-menu-icon enable"><CircleCheck /></el-icon>
                启用
              </el-dropdown-item>
              <el-dropdown-item @click="handleBatchEnable(false)">
                <el-icon class="batch-menu-icon disable"><CircleClose /></el-icon>
                禁用
              </el-dropdown-item> -->
              <el-dropdown-item @click="batchprogress('parse')" divided>
                <el-icon class="batch-menu-icon parse"><VideoPlay /></el-icon>
                解析
              </el-dropdown-item>
              <el-dropdown-item @click="batchprogress('cancel')" divided>
                <el-icon class="batch-menu-icon cancel"><Close /></el-icon>
                取消
              </el-dropdown-item>
              <el-dropdown-item @click="batchprogress('delete')" divided>
                <el-icon class="batch-menu-icon delete"><Delete /></el-icon>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div class="right-actions">
          <el-input
            v-model="queryParams.keywords"
            placeholder="搜索文件"
            clearable
            @input="handleQuery"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" icon="Plus" @click="uploadVisible = true"
            >新增文件</el-button
          >
        </div>
      </div>

      <!-- 文件表格 -->
      <div class="file-table-container" v-loading="loading">
        <el-table
          :data="fileList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column
            label="名称"
            prop="dataset_name"
            fixed="left"
            width="180"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <div class="file-name-cell">
                <div
                  v-if="getFileIconType(scope.row.dataset_name) === 'image'"
                  class="image-thumbnail"
                >
                  <img :src="scope.row.dataset_thumbnail" alt="缩略图" />
                </div>

                <!-- 其他类型：用svg-icon -->
                <template v-else>
                  <svg-icon
                    :icon-class="getSvgIconName(scope.row.dataset_name)"
                    class="el-input__icon input-icon"
                  />
                </template>
                <span
                  class="file-name-link"
                  @click="goToParseBlock(scope.row)"
                  style="cursor: pointer; color: #1677ff; font-weight: 500"
                  title="点击查看解析块"
                >
                  {{ scope.row.dataset_name }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分块数" prop="chunk_count" align="center">
            <template #default="scope">
              {{ scope.row.chunk_count || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="上传日期" prop="createTime" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="切片方法"
            prop="dataset_chunk_method"
            align="center"
          >
            <template #default="scope">
              {{ scope.row.dataset_chunk_method || "Picture" }}
            </template>
          </el-table-column>
          <el-table-column label="启用" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :loading="scope.row.enableLoading"
                @change="(val) => handleEnableChange(val, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="解析状态" width="150" align="center">
            <template #default="scope">
              <!-- 只在非未开始状态下显示tooltip -->
              <el-tooltip
                v-if="
                  scope.row.run &&
                  scope.row.run !== 'UNSTART' &&
                  scope.row.run !== '0'
                "
                placement="top"
                effect="light"
              >
                <template #content>
                  <div class="custom-tooltip-content">
                    <div class="tooltip-info-row">
                      <span class="tooltip-label">开始于:</span>
                      <span class="tooltip-value">{{
                        scope.row.process_begin_at
                      }}</span>
                    </div>
                    <div class="tooltip-info-row">
                      <span class="tooltip-label">持续时间:</span>
                      <span class="tooltip-value">{{
                        scope.row.process_duation
                      }}</span>
                    </div>
                    <div class="tooltip-info-row">
                      <span class="tooltip-label">进度:</span>
                      <span class="tooltip-value">{{
                        scope.row.progress_msg
                      }}</span>
                    </div>
                  </div>
                </template>
                <div class="parse-status-wrapper">
                  <div
                    v-if="scope.row.run === 'RUNNING'"
                    class="progress-status"
                  >
                    <span class="status-text">
                      <i class="pulse-dot"></i>解析中
                    </span>
                    <span class="percentage-text"
                      >{{ getParsePercentage(scope.row) }}.00%</span
                    >
                  </div>
                  <div
                    v-else-if="scope.row.run === 'DONE'"
                    class="success-status"
                  >
                    <span>完成</span>
                  </div>
                  <div
                    v-else-if="scope.row.run === 'FAIL'"
                    class="failed-status"
                  >
                    <span>失败</span>
                  </div>
                  <div
                    v-else-if="scope.row.run === 'CANCEL'"
                    class="cancel-status"
                  >
                    <span>取消</span>
                  </div>
                </div>
              </el-tooltip>

              <!-- 未开始状态直接显示状态框，不带tooltip -->
              <div v-else class="parse-status-wrapper">
                <div class="unstart-status">未开始</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="280"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <div class="operation-btns">
                <el-button
                  type="primary"
                  link
                  circle
                  size="small"
                  @click="handleStartParse(scope.row)"
                  title="创建解析"
                  v-if="
                    scope.row.run === 'UNSTART' ||
                    scope.row.run === 'CANCEL' ||
                    scope.row.run === '0' ||
                    !scope.row.run
                  "
                >
                  <el-icon size="20px" class="my-blue-icon"
                    ><VideoPlay
                  /></el-icon>
                </el-button>
                <el-button
                  type="primary"
                  link
                  circle
                  size="small"
                  @click="handleRefresh(scope.row)"
                  title="重新解析"
                  v-if="scope.row.run === 'DONE' || scope.row.run === 'FAIL'"
                >
                  <el-icon size="20px" class="my-blue-icon"
                    ><RefreshRight
                  /></el-icon>
                </el-button>
                <!-- 仅解析中时显示停止解析按钮 -->
                <el-button
                  v-if="scope.row.run === 'RUNNING'"
                  type="danger"
                  circle
                  size="small"
                  @click="handleParseStop(scope.row, 'singleCancel')"
                  title="停止解析"
                  class="stop-parse-btn"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
                <el-button
                  type="primary"
                  link
                  circle
                  size="small"
                  @click="handleEdit(scope.row)"
                  title="编辑"
                  :disabled="scope.row.run === 'RUNNING'"
                  class="op-btn"
                >
                  <el-icon class="op-black-icon"><Edit /></el-icon>
                </el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="primary"
                  link
                  circle
                  size="small"
                  @click="handleDelete(scope.row, 'singleDelete')"
                  title="删除"
                  :disabled="scope.row.run === 'RUNNING'"
                  class="op-btn"
                >
                  <el-icon class="op-black-icon"><Delete /></el-icon>
                </el-button>
                <!-- 下载按钮 -->
                <el-button
                  type="primary"
                  link
                  circle
                  size="small"
                  @click="handleExport(scope.row)"
                  title="下载"
                  :disabled="scope.row.run === 'RUNNING'"
                  class="op-btn"
                >
                  <el-icon class="op-black-icon"><Download /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-footer">
        <div class="total-count">总共 {{ total }}</div>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <div class="page-info">{{ queryParams.pageSize }} 条/页</div>
      </div>
    </div>

    <!-- 上传文件对话框 -->
    <el-dialog
      title="上传文件"
      v-model="uploadVisible"
      width="500px"
      :close-on-click-modal="false"
      class="upload-dialog"
      @closed="handleDialogClosed"
      append-to-body
    >
      <el-tabs v-model="activeTab" class="file-upload-tabs">
        <el-tab-pane label="文件" name="local">
          <div class="upload-area">
            <el-upload
              ref="uploadRef"
              class="custom-upload"
              drag
              :http-request="() => {}"
              :on-change="handleFileChange"
              :file-list="uploadFileList"
              :auto-upload="false"
              :show-file-list="false"
              multiple
            >
              <div class="upload-content">
                <div class="upload-icon-wrapper">
                  <i class="upload-box-icon"></i>
                </div>
                <div class="upload-text">点击或拖拽文件至此区域即可上传</div>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持所有文件类型，单个文件大小不超过20MB
                </div>
              </template>
            </el-upload>

            <!-- 自定义文件列表 -->
            <div v-if="uploadFileList.length > 0" class="custom-file-list">
              <div class="files-header">
                <span>文件列表 (总计 {{ uploadFileList.length }} 个文件)</span>
              </div>
              <el-scrollbar height="250px">
                <ul class="file-list">
                  <li
                    v-for="(file, index) in uploadFileList"
                    :key="index"
                    class="file-item"
                  >
                    <div class="file-item-icon">
                      <div
                        v-if="getFileIconType(file.name) === 'image'"
                        class="image-thumbnail"
                      >
                        <img :src="getFileObjectUrl(file)" alt="缩略图" />
                      </div>
                      <el-icon v-else><Document /></el-icon>
                    </div>
                    <div class="file-item-info">
                      <div class="file-item-name" :title="file.name">
                        {{ file.name }}
                      </div>
                      <div class="file-item-size">
                        {{ formatFileSize(file.size || 0) }}
                      </div>
                    </div>
                    <div class="file-item-actions">
                      <el-button
                        type="danger"
                        icon="Delete"
                        circle
                        size="small"
                        @click="removeUploadFile(index)"
                      ></el-button>
                    </div>
                  </li>
                </ul>
              </el-scrollbar>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="文件夹" name="folder">
          <div class="upload-area">
            <div
              class="upload-content folder-upload-content"
              @click="selectFolder"
              @dragover.prevent
              @drop="handleFolderDrop"
            >
              <div class="upload-icon-wrapper">
                <i class="upload-folder-icon"></i>
              </div>
              <div class="upload-text">点击选择文件夹或拖拽文件夹至此区域</div>

              <!-- 隐藏的文件夹选择输入框 -->
              <input
                type="file"
                ref="folderInput"
                webkitdirectory
                directory
                multiple
                style="display: none"
                @change="handleFolderSelect"
              />
            </div>

            <!-- 显示所有文件列表 -->
            <div v-if="folderFiles.length > 0" class="folder-files-list">
              <div class="files-header">
                <span>文件列表 (总计 {{ folderFiles.length }} 个文件)</span>
              </div>
              <el-scrollbar height="250px">
                <ul class="file-list">
                  <li
                    v-for="(file, index) in folderFiles"
                    :key="index"
                    class="file-item"
                  >
                    <div class="file-item-icon">
                      <div
                        v-if="getFileIconType(file.name) === 'image'"
                        class="image-thumbnail"
                      >
                        <img :src="getImageUrl(file)" alt="缩略图" />
                      </div>
                      <el-icon v-else><Document /></el-icon>
                    </div>
                    <div class="file-item-info">
                      <div
                        class="file-item-name"
                        :title="file.relativePath || file.webkitRelativePath"
                      >
                        {{ getFileName(file) }}
                      </div>
                      <div class="file-item-path">
                        {{ getFolderPath(file) }}
                      </div>
                      <div class="file-item-size">
                        {{ formatFileSize(file.size) }}
                      </div>
                    </div>
                    <div class="file-item-actions">
                      <el-button
                        type="danger"
                        icon="Delete"
                        circle
                        size="small"
                        @click="removeFileFromFolder(index)"
                      ></el-button>
                    </div>
                  </li>
                </ul>
              </el-scrollbar>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="parse-option">
        <el-checkbox v-model="createWithParse">创建时解析</el-checkbox>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadVisible = false" :disabled="uploadLoading"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="confirmUpload"
            :loading="uploadLoading"
            >{{ uploadLoading ? "上传中..." : "确 定" }}</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog
      title="重命名"
      v-model="renameVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        :model="renameForm"
        :rules="renameRules"
        ref="renameFormRef"
        label-width="80px"
      >
        <el-form-item label="名称:" prop="name" required>
          <el-input v-model="renameForm.name" placeholder="请输入文件名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renameVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmRename">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Document,
  Search,
  Download,
  Upload,
  Calendar,
  User,
  Edit,
  Delete,
  RefreshRight,
  ArrowDown,
  Warning,
  UploadFilled,
  Folder,
  FolderOpened,
  VideoPlay,
  CircleCheck,
  CircleClose,
  FolderAdd,
  Close,
  Picture,
  Headset,
  VideoCameraFilled,
  Files,
  Connection,
  Memo,
} from "@element-plus/icons-vue";
import { parseTime } from "@/utils/ruoyi";
import { getToken } from "@/utils/auth";
import {
  listFile,
  parseDocument,
  getParseStatus,
  deleteChunk,
  listChunk,
  deleteFile,
  updateFile,
  downFile,
  parseStop,
} from "@/api/knowledge/dataset";
import request from "@/utils/request"; // 导入请求工具
import { ro } from "element-plus/es/locales.mjs";
import { ElLoading, ElMessage } from "element-plus";
import { blobValidate } from "@/utils/ruoyi";
import { saveAs } from "file-saver";
import service from "@/utils/request";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
let datasetId = ref(computed(() => route.params.id));
const ids = localStorage.getItem("ids");
let dataset_name = ref("");
if (ids) {
  const idsObj = JSON.parse(ids);
  console.log(idsObj.dataset_id, "idsObj");
  datasetId.value = idsObj.dataset_id;
  dataset_name.value = idsObj.dataset_name;
  console.log(dataset_name.value, "dataset_name");
}
console.log(ids, "ids");
// 查询参数
const queryParams = reactive({
  dataset_id: datasetId.value,
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

// 数据相关
const loading = ref(false);
const fileList = ref([]);
const total = ref(0);
const selectedRows = ref([]);

// 上传相关
const uploadRef = ref(null);
const uploadVisible = ref(false);
const activeTab = ref("local");
const createWithParse = ref(false);
const uploadFileList = ref([]);

// 文件夹上传相关
const folderInput = ref(null);
const folderFiles = ref([]);
const folderName = ref("");
const folderGroups = ref([]); // 新增：用于存储多个文件夹分组信息

// 文件重命名相关
const renameVisible = ref(false);
const renameFormRef = ref(null);
const renameForm = ref({
  chunk_method: "",
  name: "",
  document_id: "",
});
const renameRules = {
  name: [
    { required: true, message: "请输入文件名称", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
  ],
};

// 添加上传加载状态
const uploadLoading = ref(false);

// 使用环境变量构建完整URL
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = computed(() => {
  // 确保baseUrl以/结尾，路径以/开头
  const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
  return `${base}/ai/dataset/upload/document/${datasetId.value}`;
});

// 从公共方法获取请求头
const uploadHeaders = computed(() => {
  return {
    Authorization: "Bearer " + getToken(),
    // 可以在这里添加其他必要的头部信息
  };
});

// 格式化日期
function formatDate(timestamp, format = "{y}-{m}-{d} {h}:{i}:{s}") {
  return parseTime(timestamp, format);
}

// 获取状态类型
function getStatusType(status) {
  switch (status) {
    case "DONE":
    case "完成":
      return "success";
    case "RUNNING":
    case "解析中":
      return "warning";
    case "FAIL":
    case "失败":
      return "danger";
    case "CANCEL":
    case "取消":
      return "info";
    case "UNSTART":
    case "0":
    default:
      return "info";
  }
}

// 获取状态文本
function getStatusText(status) {
  switch (status) {
    case "DONE":
    case "完成":
      return "完成";
    case "RUNNING":
    case "解析中":
      return "解析中";
    case "FAIL":
    case "失败":
      return "失败";
    case "CANCEL":
    case "取消":
      return "取消";
    case "UNSTART":
    case "0":
    default:
      return "未开始";
  }
}

// 获取解析进度百分比
function getParsePercentage(row) {
  return row.progress ? Math.floor(row.progress * 100) : 0;
}

// 进度条显示格式
function percentageFormat(percentage) {
  return percentage ? `${percentage}%` : "0%";
}

// 获取进度条状态
function getProgressStatus(row) {
  const percentage = getParsePercentage(row);
  if (percentage >= 100) {
    return "success";
  } else if (percentage > 0) {
    return "warning";
  }
  return "warning";
}

// 获取文件列表
function getFileList() {
  loading.value = true;
  listFile(queryParams).then((response) => {
    loading.value = false;
    // 初始化每行的 enableLoading 字段
    fileList.value = (response.data.rows || []).map((row) => ({
      ...row,
      status: row.status == "1" ? true : false,
      enableLoading: false,
    }));
    //  获取所有正在解析的文件id
    let documentIds = []
    documentIds = fileList.value.filter((item)=>{
      return item.run == "RUNNING"
    }).map((item)=>{
      return item.document_id
    })
    if(documentIds.length > 0){
      pollParseStatus(documentIds)
    }
    total.value = response.data.total;
  });
}

// 处理选择变化
function handleSelectionChange(selection) {
  selectedRows.value = selection;
}

// 处理启用状态变化
function handleEnableChange(value, row) {
  // 记录原始状态
  const oldState = !value;
  row.enableLoading = true;
  const params = {
    name: row.dataset_name,
    // chunk_method: row.dataset_chunk_method,
    enabled: value,
    document_id: row.document_id,
  };
  updateFile(params)
    .then((res) => {
      if (res.code !== 200) {
        // 接口失败，回滚状态
        row.status = oldState;
        proxy.$modal.msgError(res.msg || "操作失败");
      }else{
        proxy.$modal.msgSuccess("操作成功");
        getFileList();
      }
    })
    .catch(() => {
      row.status = oldState;
      proxy.$modal.msgError("操作失败");
    })
    .finally(() => {
      row.enableLoading = false;
    });
}

// 轮询获取解析状态，直到progress等于1
async function pollParseStatus(documentIds, maxAttempts = 1000) {
  let attempts = 0;

  async function poll() {
    // if (attempts >= maxAttempts) {
    //   console.log("轮询次数达到上限，停止轮询");
    //   return;
    // }
    attempts++;

    try {
      const response = await getParseStatus(queryParams);
      if (response && response.data) {
        const rows = Array.isArray(response.data.rows)
          ? response.data.rows
          : [];
        const runningRows = rows.filter((item) =>
          documentIds.includes(item.document_id?.toString())
        );
        updateFileProgress(documentIds, rows);

        // 只要有 CANCEL 或全部 progress==1 就停止
        if (
          runningRows.length > 0 &&
          (runningRows.every((item) => item.progress == 1) ||
            runningRows.some((item) => item.run === "FAIL") ||
            runningRows.some((item) => item.run === "CANCEL"))
        ) {
          setTimeout(() => getFileList(), 1000);
          return;
        } else {
          setTimeout(poll, 3000);
        }
      } else {
        setTimeout(poll, 3000);
      }
    } catch (error) {
      setTimeout(poll, 5000);
    }
  }
  await poll();
}

// 批量更新文件列表中多个文件的解析进度
function updateFileProgress(documentIds, rows) {
  if (!Array.isArray(documentIds) || !Array.isArray(rows)) return;
  documentIds.forEach((documentId) => {
    const progressInfo = rows.find(
      (row) => row.document_id?.toString() === documentId?.toString()
    );
    if (!progressInfo) return;
    const fileIndex = fileList.value.findIndex(
      (file) => file.document_id?.toString() === documentId?.toString()
    );
    if (fileIndex === -1) return;
    const progress = progressInfo.progress;
    if (progress > 0 && progress < 1) {
      fileList.value[fileIndex].run = "RUNNING";
      fileList.value[fileIndex].progress = progress;
    } else if (progress === 1) {
      fileList.value[fileIndex].run = "DONE";
      fileList.value[fileIndex].progress = progress;
    } else if (progress === 0) {
      fileList.value[fileIndex].run = "UNSTART";
      fileList.value[fileIndex].progress = progress;
    }
  });
}

// 在handleStartParse成功后调用
async function handleStartParse(row) {
  console.log(row);
  const data = {
    dataset_id: datasetId.value.toString(),
    document_ids: [row.document_id.toString()],
  };

  parseDocument(data)
    .then((response) => {
      console.log(88);
      if (response.code === 200) {
        proxy.$modal.msgSuccess("文件解析任务已提交");

        // 构建getParseStatus所需的参数
        const params = {
          dataset_id: datasetId.value.toString(),
          document_id: row.document_id.toString(),
        };

        // 开始轮询
        pollParseStatus([row.document_id.toString()]);
      } else {
        proxy.$modal.msgError(response.msg || "解析任务提交失败");
      }
    })
    .catch((error) => {
      console.log(8888);
      proxy.$modal.msgError("解析任务提交失败: " + (error.message || error));
    });
}

// 处理刷新（重新解析）
function handleRefresh(row) {
  startReparseDocument(row);
  // 首先检查是否有分块
  // const chunkCount = row.chunk_count || 0;

  // if (chunkCount > 0) {
  //   // 有分块，询问是否清空
  //   proxy.$modal
  //     .confirm(
  //       `文件"${
  //         row.fileName || row.dataset_name
  //       }"有${chunkCount}个分块数据，是否需要清空分块后重新解析？`,
  //       "清空确认",
  //       {
  //         confirmButtonText: "清空并重新解析",
  //         cancelButtonText: "直接重新解析",
  //         type: "warning",
  //       }
  //     )
  //     .then(() => {
  //       // 确认按钮点击，清空分块并重新解析
  //       console.log("用户选择了清空分块");
  //       clearChunksAndReparse(row);
  //     })
  //     .catch((action) => {
  //       // 取消按钮点击，直接重新解析
  //       if (action === "cancel") {
  //         console.log("用户选择不清空分块，直接解析");
  //         startReparseDocument(row);
  //       }
  //     });
  // } else {
  //   // 没有分块，直接开始解析，无需确认
  //   startReparseDocument(row);
  // }
}

// 清空分块并重新解析
async function clearChunksAndReparse(row) {
  console.log("执行清空分块函数", row);
  try {
    // 显示正在清空分块的提示
    // proxy.$modal.msgInfo(`正在获取文件"${row.fileName || row.dataset_name}"的分块数据...`);

    // 首先获取分块列表
    const listParams = {
      dataset_uuid: row.dataset_dataset_uuid.toString(),
      document_uuid: row.dataset_document_uuid.toString(),
      pageSize: 100, // 设置较大的页面大小以获取所有分块
      pageNum: 1,
    };

    // console.log('获取分块列表参数:', listParams);

    // 调用listChunk接口获取分块列表
    const listResponse = await listChunk(listParams);
    console.log("分块列表响应:", listResponse);

    if (listResponse && listResponse.data && listResponse.data.data) {
      // 提取分块ID
      const chunkIds = listResponse.data.data?.chunks.map((chunk) =>
        chunk.id.toString()
      );
      console.log("获取到的分块ID:", chunkIds);

      // if (chunkIds.length === 0) {
      //   proxy.$modal.msgWarning("未找到分块数据，将直接进行解析");
      //   startReparseDocument(row);
      //   return;
      // }

      // proxy.$modal.msgInfo(`找到${chunkIds.length}个分块，正在清空...`);

      // 构建清空分块的请求参数
      const chunkParams = {
        chunk_ids: chunkIds,
        dataset_uuid: row.dataset_dataset_uuid.toString(),
        document_uuid: row.dataset_document_uuid.toString(),
      };

      // console.log("清空分块请求参数:", chunkParams);

      // 调用清空分块API
      const deleteResponse = await deleteChunk(chunkParams);
      console.log("清空分块响应:", deleteResponse);

      if (deleteResponse.code === 200) {
        proxy.$modal.msgSuccess(
          `已清空${chunkIds.length}个分块数据，正在开始重新解析...`
        );
        // 清空成功后开始重新解析
        startReparseDocument(row);
      } else {
        proxy.$modal.msgError(deleteResponse.msg || "清空分块失败");
      }
    } else {
      proxy.$modal.msgError("获取分块列表失败，将直接进行解析");
      startReparseDocument(row);
    }
  } catch (error) {
    console.error("清空分块过程出错:", error);
    proxy.$modal.msgError("处理分块失败: " + (error.msg || error));
    // 出错时也尝试直接进行解析
    startReparseDocument(row);
  }
}

// 开始批量解析文档
function startReparseDocument(row) {
  console.log(row, "row");

  let documentIds = [];
  if (Array.isArray(row)) {
    // 批量解析
    documentIds = row
      .map((item) => {
        const docId = item.document_id;
        return docId ? docId?.toString() : null;
      })
      .filter((id) => id !== null); // 过滤掉null值
  } else {
    // 单个解析
    const docId = row.document_id;
    if (docId) {
      documentIds = [];
      documentIds.push(docId.toString());
      console.log("从单个对象提取的document_id:", docId);
    }
  }
  // 构建请求参数
  const data = {
    dataset_id: datasetId.value.toString(),
    document_ids: documentIds,
  };

  // 调用解析API
  parseDocument(data)
    .then((response) => {
      if (response.code === 200) {
        const params = {
          dataset_id: datasetId.value.toString(),
          // document_id: row.document_id.toString() || row.id.toString(),
        };

        // 开始轮询
        pollParseStatus(documentIds);

        // 刷新文件列表
        // getFileList();
      } else {
        proxy.$modal.msgError(response.msg || "解析任务提交失败");
      }
    })
    .catch((error) => {
      proxy.$modal.msgError("解析任务提交失败: " + (error.message || error));
    });
}

// 处理编辑(重命名)
function handleEdit(row) {
  console.log(row, "rr");
  renameForm.value.name = row.dataset_name;
  renameForm.value.chunk_method = row.dataset_chunk_method;
  console.log(renameForm.value, "renameForm.value.name");
  renameForm.value.document_id = row.document_id;
  // renameForm.value = Object.assign({}, renameForm.value, row); chunk_method
  renameVisible.value = true;
}

// 处理查询
function handleQuery() {
  queryParams.pageNum = 1;
  getFileList();
}

// 处理页面大小变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  getFileList();
}

// 处理当前页变化
function handleCurrentChange(page) {
  queryParams.pageNum = page;
  getFileList();
}

// 处理下载文件
function handleExport(row) {
  // 设置下载URL（带路径参数的GET请求）
  const downloadUrl = `/ai/dataset/download/document/${row.document_id}`;

  // 显示加载中提示
  const downloadLoadingInstance = ElLoading.service({
    text: "正在下载文件，请稍候",
    background: "rgba(0, 0, 0, 0.7)",
  });

  // 提取原始文件名和后缀
  const originalName = row.dataset_name || "file";
  const dotIndex = originalName.lastIndexOf(".");
  let baseName = originalName;
  let ext = "";
  if (dotIndex !== -1) {
    baseName = originalName.substring(0, dotIndex);
    ext = originalName.substring(dotIndex); // 包含点
  } else {
    ext = ".bin"; // 没有后缀时默认
  }
  const fileName = `${baseName}_${new Date().getTime()}${ext}`;

  // 使用GET请求下载文件
  service
    .get(downloadUrl, {
      responseType: "blob",
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, fileName);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      ElMessage.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

// 处理删除文件
function handleDelete(row, type) {
  console.log("handleDelete called with:", row); // 调试日志

  // 判断是单个还是批量
  let documentIds = [];
  if (row && type == "singleDelete") {
    documentIds = [row.document_id.toString()];
  } else {
    if (!selectedRows.value.length) {
      proxy.$modal.msgWarning("请先选择要删除的文件");
      return;
    }
    documentIds = selectedRows.value.map((item) => item.document_id.toString());
  }

  console.log("Document IDs to delete:", documentIds); // 调试日志

  const isBatch = !row;
  const confirmMsg = isBatch
    ? `确定要删除选中的 ${documentIds.length} 个文件吗？删除后不可恢复。`
    : `确定要删除文件吗？删除后不可恢复。`;

  proxy.$modal
    .confirm(confirmMsg)
    .then(() => {
      console.log("User confirmed deletion"); // 调试日志
      const data = {
        dataset_id: datasetId.value.toString(),
        document_ids: documentIds,
      };
      console.log("Calling deleteFile with:", data); // 调试日志

      console.log("准备调用 deleteFile，参数：", data, deleteFile);
      deleteFile(data)
        .then((response) => {
          console.log("Delete response:", response); // 调试日志
          if (response.code === 200) {
            proxy.$modal.msgSuccess(isBatch ? "批量删除成功" : "删除成功");
            getFileList();
          } else {
            proxy.$modal.msgError(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("Delete error:", error); // 调试日志
          proxy.$modal.msgError("删除失败");
        })
        .finally(() => {});
    })
    .catch(() => {
      console.log("User cancelled deletion"); // 调试日志
    });
}

// 上传前的验证
function beforeUpload(file) {
  // 仅检查文件大小
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    proxy.$modal.msgError("文件大小不能超过 20MB!");
    return false;
  }

  return true;
}

// 上传成功处理
function handleUploadSuccess(response, file, fileList) {
  if (response.code === 200) {
    proxy.$modal.msgSuccess("文件上传成功");

    // 上传完毕后刷新文件列表
    if (
      fileList.length === fileList.filter((f) => f.status === "success").length
    ) {
      getFileList();
      uploadVisible.value = false;
      loading.value = false;
    }
  } else {
    proxy.$modal.msgError(response.msg || "文件上传失败");
    loading.value = false;
  }
}

// 上传错误处理
function handleUploadError(error, file, fileList) {
  proxy.$modal.msgError("文件上传失败: " + (error.message || error));
  loading.value = false;
}

// 修改confirmUpload函数
async function confirmUpload() {
  if (activeTab.value === "local") {
    console.log("Upload files:", uploadFileList.value);

    // 检查是否有文件要上传
    if (uploadFileList.value && uploadFileList.value.length > 0) {
      uploadLoading.value = true; // 设置上传加载状态为true

      try {
        // 创建FormData对象
        const formData = new FormData();
        uploadFileList.value.forEach((file) => {
          // 只添加raw属性存在的文件（未上传的文件）
          if (file.raw) {
            formData.append("file", file.raw);
          }
        });
        await handleuploadFile(formData);
      } catch (error) {
        proxy.$modal.msgError("文件上传失败: " + (error.msg || error));
      } finally {
        uploadLoading.value = false; // 无论成功失败都重置加载状态
      }
    } else {
      proxy.$modal.msgWarning("请先选择要上传的文件");
    }
  } else if (activeTab.value === "folder") {
    // 文件夹上传逻辑
    if (folderFiles.value && folderFiles.value.length > 0) {
      uploadLoading.value = true; // 设置上传加载状态为true

      try {
        // 创建FormData对象
        const formData = new FormData();

        // 添加所有文件，保留相对路径信息
        folderFiles.value.forEach((file) => {
          // 使用相对路径作为文件名，确保服务器能保留文件夹结构
          formData.append(
            "file",
            file,
            file.relativePath || file.webkitRelativePath
          );
        });

        // 发送请求
        await handleuploadFile(formData);
        uploadVisible.value = false;
      } catch (error) {
        proxy.$modal.msgError("文件夹上传失败: " + (error.message || error));
      } finally {
        uploadLoading.value = false; // 无论成功失败都重置加载状态
      }
    } else {
      proxy.$modal.msgWarning("请先选择要上传的文件夹");
    }
  }
}

// 修改handleuploadFile函数为async/await模式，并增加超时显示
const handleuploadFile = async (formData) => {
  // 使用request模块发送请求
  const response = await request({
    url: `/ai/dataset/upload/document/${datasetId.value}`,
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  console.log(response);
  if (response.code == 200) {
    // 处理响应
    if (createWithParse.value) {
      startReparseDocument(response.data);
    }
    proxy.$modal.msgSuccess(`文件 ${folderName.value} 上传成功`);
    getFileList();
    uploadVisible.value = false;
  } else {
    proxy.$modal.msgError(response.msg || "文件上传失败");
  }
  getFileList();
};
// 处理文件变化
function handleFileChange(file, fileList) {
  console.log("File change:", file, fileList);
  // 更新文件列表状态
  uploadFileList.value = fileList;
}

// 处理对话框关闭
function handleDialogClosed() {
  // 清空已选文件
  uploadFileList.value = [];
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  // 清空已选文件夹
  clearFolderSelection();

  // 重置加载状态
  uploadLoading.value = false;
}

// 点击选择文件夹
function selectFolder() {
  folderInput.value.click();
}

// 处理文件夹选择
function handleFolderSelect(event) {
  const files = event.target.files;
  if (files && files.length > 0) {
    // 获取文件夹名称（从第一个文件的路径中获取）
    const firstFilePath = files[0].webkitRelativePath;
    const currentFolderName = firstFilePath.split("/")[0];

    // 将文件数组转换为普通数组
    const newFiles = Array.from(files);

    // 检查是否已经添加过该文件夹
    const existingGroupIndex = folderGroups.value.findIndex(
      (group) => group.name === currentFolderName
    );

    if (existingGroupIndex !== -1) {
      // 如果已存在该文件夹，更新其文件
      folderGroups.value[existingGroupIndex].files = newFiles;
    } else {
      // 否则添加新的文件夹分组
      folderGroups.value.push({
        name: currentFolderName,
        files: newFiles,
      });
    }

    // 更新总文件列表
    updateFolderFiles();

    console.log(
      `已添加文件夹: ${currentFolderName}，包含 ${newFiles.length} 个文件`
    );
  }
}

// 更新总文件列表
function updateFolderFiles() {
  // 将所有文件夹的文件合并到一个数组
  folderFiles.value = [];
  folderGroups.value.forEach((group) => {
    folderFiles.value = folderFiles.value.concat(group.files);
  });
}

// 选择额外的文件夹
function selectAdditionalFolder() {
  // 清空input的值，确保相同文件夹可以再次选择
  if (folderInput.value) {
    folderInput.value.value = "";
  }
  folderInput.value.click();
}

// 清空所有文件夹
function clearAllFolders() {
  folderGroups.value = [];
  folderFiles.value = [];
  folderName.value = "";
}

// 移除指定的文件夹组
function removeFolderGroup(groupIndex) {
  folderGroups.value.splice(groupIndex, 1);
  updateFolderFiles();

  // 如果没有文件夹了，清空文件夹名称
  if (folderGroups.value.length === 0) {
    folderName.value = "";
  }
}

// 从文件夹中移除文件
function removeFileFromFolder(fileIndex) {
  const fileToRemove = folderFiles.value[fileIndex];
  const filePath = fileToRemove.webkitRelativePath || fileToRemove.relativePath;
  const folderName = filePath.split("/")[0];

  // 找到对应的文件夹组
  const groupIndex = folderGroups.value.findIndex(
    (group) => group.name === folderName
  );

  if (groupIndex !== -1) {
    // 从该组中移除文件
    const group = folderGroups.value[groupIndex];
    const fileIndexInGroup = group.files.findIndex(
      (f) => f.webkitRelativePath === filePath || f.relativePath === filePath
    );

    if (fileIndexInGroup !== -1) {
      group.files.splice(fileIndexInGroup, 1);

      // 如果该组没有文件了，移除整个组
      if (group.files.length === 0) {
        folderGroups.value.splice(groupIndex, 1);
      }
    }
  }

  // 从总文件列表中移除
  folderFiles.value.splice(fileIndex, 1);
}

// 获取文件名（从路径中提取）
function getFileName(file) {
  // 尝试从relativePath获取，如果没有则从webkitRelativePath获取
  const path = file.relativePath || file.webkitRelativePath || file.name;
  return path.split("/").pop(); // 获取路径最后一部分作为文件名
}

// 获取文件所在的文件夹路径
function getFolderPath(file) {
  const fullPath = file.relativePath || file.webkitRelativePath || "";
  const pathParts = fullPath.split("/");

  // 如果路径至少有两部分（文件夹名和文件名）
  if (pathParts.length >= 2) {
    // 返回不包含最后一部分的路径
    return pathParts.slice(0, -1).join("/");
  }
  return pathParts[0]; // 仅返回文件夹名
}

// 处理文件夹拖放 - 修改为支持多文件夹
function handleFolderDrop(event) {
  event.preventDefault();

  // 获取拖放的项目
  const items = event.dataTransfer.items;
  if (!items) return;

  // 处理拖放项目
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    // 检查是否是文件夹（webkitGetAsEntry API）
    if (item.kind === "file") {
      const entry = item.webkitGetAsEntry();
      if (entry && entry.isDirectory) {
        // 找到文件夹，记录名称
        const droppedFolderName = entry.name;

        // 创建一个临时数组来存储此文件夹的文件
        const tempFiles = [];

        // 开始读取文件夹内容
        readFolderEntry(entry, "", tempFiles, () => {
          // 读取完成后的回调
          if (tempFiles.length > 0) {
            // 检查是否已存在该文件夹
            const existingGroupIndex = folderGroups.value.findIndex(
              (group) => group.name === droppedFolderName
            );

            if (existingGroupIndex !== -1) {
              // 更新现有文件夹
              folderGroups.value[existingGroupIndex].files = tempFiles;
            } else {
              // 添加新文件夹
              folderGroups.value.push({
                name: droppedFolderName,
                files: tempFiles,
              });
            }

            // 更新总文件列表
            updateFolderFiles();
          }
        });
      }
    }
  }
}

// 递归读取文件夹条目内容 - 修改为支持回调
function readFolderEntry(
  entry,
  path = "",
  fileArray = [],
  callback = null,
  pendingCallbacks = { count: 0 }
) {
  pendingCallbacks.count++;

  if (entry.isFile) {
    // 是文件，获取File对象
    entry.file((file) => {
      // 添加完整路径信息
      const fullPath = path ? `${path}/${entry.name}` : entry.name;
      // 创建新的File对象，添加路径信息
      const fileWithPath = new File([file], entry.name, { type: file.type });
      fileWithPath.relativePath = fullPath;
      fileArray.push(fileWithPath);

      pendingCallbacks.count--;
      if (pendingCallbacks.count === 0 && callback) {
        callback();
      }
    });
  } else if (entry.isDirectory) {
    // 是文件夹，继续读取
    const dirReader = entry.createReader();
    // 递归读取目录内容
    const readEntries = () => {
      dirReader.readEntries((entries) => {
        if (entries.length) {
          const newPath = path ? `${path}/${entry.name}` : entry.name;
          for (let i = 0; i < entries.length; i++) {
            readFolderEntry(
              entries[i],
              newPath,
              fileArray,
              callback,
              pendingCallbacks
            );
          }
          // 继续读取，因为可能有更多条目
          readEntries();
        } else {
          pendingCallbacks.count--;
          if (pendingCallbacks.count === 0 && callback) {
            callback();
          }
        }
      });
    };
    readEntries();
  }
}

// 清空文件夹选择 - 更新为支持多文件夹
function clearFolderSelection() {
  folderFiles.value = [];
  folderGroups.value = [];
  folderName.value = "";
  if (folderInput.value) {
    folderInput.value.value = "";
  }
}

// 批量处理
function batchprogress(action) {
  const selection = selectedRows.value;
  if (!selection || selection.length === 0) {
    proxy.$modal.msgWarning("请先选择要操作的文件");
    return;
  }

  switch (action) {
    case "enable":
      proxy.$modal.msgInfo("批量启用功能开发中");
      break;
    case "cancel":
      handleParseStop(selection, "batchCancel");
      break;
    case "parse":
      startReparseDocument(selection);
      break;
    case "delete":
      handleDelete(selection, "batchDelete");
      break;
  }
}

// 批量解析
function batchParse(selection) {
  // console.log(selection, "selection");
  // const documentIds = selection.map((item) =>
  //       (item.document_id).toString()
  //     );
  //     console.log(documentIds, "documentIds");
  //     // 构建请求参数
  //     const data = {
  //       dataset_id: datasetId.value.toString(),
  //       document_ids: documentIds,
  //     };
  // // 调用解析API
  // parseDocument(data)
  //   .then((response) => {
  //     console.log(9999);
  //     if (response.code === 200) {
  //       proxy.$modal.msgSuccess("批量解析任务已提交");
  //       // 刷新文件列表
  //       getFileList();
  //     } else {
  //       proxy.$modal.msgError(response.msg || "批量解析任务提交失败");
  //     }
  //   })
  //   .catch((error) => {
  //     proxy.$modal.msgError(
  //       "批量解析任务提交失败: " + (error.message || error)
  //     );
  //   });
}

// 确认重命名
function confirmRename() {
  renameFormRef.value.validate(async (valid) => {
    if (valid) {
      updateFile(renameForm.value).then((res) => {
        if (res.code == 200) {
          renameVisible.value = false;
          getFileList();
        }
      });
    } else {
      return false;
    }
  });
}

// 格式化文件大小
function formatFileSize(size) {
  if (size < 1024) {
    return size + " B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + " KB";
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(1) + " MB";
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(1) + " GB";
  }
}

// 手动删除上传文件
function removeUploadFile(index) {
  // 获取要删除的文件
  const fileToRemove = uploadFileList.value[index];

  // 从数组中删除文件
  uploadFileList.value.splice(index, 1);

  // 如果uploadRef可用，同步更新组件内部状态
  if (uploadRef.value && fileToRemove && fileToRemove.uid) {
    try {
      // 尝试调用组件内部的移除方法
      uploadRef.value.handleRemove(fileToRemove);
    } catch (err) {
      console.error("Error removing file from upload component:", err);
    }
  }
}

// 根据文件名获取图标类型
function getFileIconType(fileName) {
  if (!fileName) return "document";

  const extension = fileName.split(".").pop().toLowerCase();

  // 图片类型
  if (["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"].includes(extension)) {
    return "image";
  }

  // 文档类型
  if (["doc", "docx", "odt"].includes(extension)) {
    return "word";
  }

  // Excel类型
  if (["xls", "xlsx", "csv"].includes(extension)) {
    return "excel";
  }

  // PDF类型
  if (extension === "pdf") {
    return "pdf";
  }

  // 音频类型
  if (["mp3", "wav", "ogg", "flac", "m4a"].includes(extension)) {
    return "audio";
  }

  // 视频类型
  if (["mp4", "webm", "mov", "avi", "mkv"].includes(extension)) {
    return "video";
  }

  // 压缩包类型
  if (["zip", "rar", "7z", "tar", "gz"].includes(extension)) {
    return "zip";
  }

  // 代码/编程文件类型
  if (
    [
      "js",
      "ts",
      "py",
      "java",
      "c",
      "cpp",
      "html",
      "css",
      "php",
      "rb",
      "go",
      "json",
      "xml",
    ].includes(extension)
  ) {
    return "code";
  }

  // 文本文件类型
  if (["txt", "md", "rtf"].includes(extension)) {
    return "text";
  }

  // 默认文档类型
  return "document";
}

// 获取文件图标的CSS类名
function getFileIconClass(row) {
  if (!row.dataset_name) return "";

  const extension = row.dataset_name.split(".").pop().toLowerCase();

  // 返回基于文件扩展名的CSS类名
  return `file-icon-${extension}`;
}

// 获取图片URL
function getImageUrl(row) {
  // 如果您的图片有特定的访问URL，使用该URL
  // 例如：return `${baseUrl}/api/files/${row.document_id}/preview`;

  // 如果您存储了图片的完整URL
  if (row.dataset_thumbnail) {
    return row.dataset_thumbnail;
  }
}

// 获取本地文件的对象URL用于预览
function getFileObjectUrl(file) {
  if (file.raw) {
    return URL.createObjectURL(file.raw);
  }
  return "";
}

// 根据文件名获取svg-icon名称
function getSvgIconName(name) {
  if (!name) return "document";
  const ext = name.split(".").pop().toLowerCase();
  if (["xls", "xlsx", "csv"].includes(ext)) return "xls";
  if (["doc", "docx", "odt"].includes(ext)) return "doc";
  if (ext === "pdf") return "pdf";
  if (["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"].includes(ext))
    return "image";
  if (["mp3", "wav", "ogg", "flac", "m4a"].includes(ext)) return "audio";
  if (["mp4", "webm", "mov", "avi", "mkv"].includes(ext)) return "video";
  if (["zip", "rar", "7z", "tar", "gz"].includes(ext)) return "zip";
  if (
    [
      "js",
      "ts",
      "py",
      "java",
      "c",
      "cpp",
      "html",
      "css",
      "php",
      "rb",
      "go",
      "json",
      "xml",
    ].includes(ext)
  )
    return "json";
  if (["txt", "md", "rtf"].includes(ext)) return "txt";
  return "document";
}

function goToParseBlock(row) {
  // 假设解析块详情页路由为 /knowledge/dataset/parse-block/:document_id
  proxy.$router.push({
    path: `/knowledge/dataset/chunk/`,
    query: {
      document_id: row.dataset_document_uuid,
      dataset_id: row.dataset_dataset_uuid,
      name: row.dataset_name,
    },
  });
}
//

function handleParseStop(row, type) {
  console.log(row, "row");
  // 声明变量时需要使用 let 或 const
  let params = {};

  if (row && type == "singleCancel") {
    params = {
      dataset_id: datasetId.value.toString(),
      document_ids: [row.document_id.toString()],
    };
  }

  console.log(selectedRows.value, "selectedRows.value");
  if (selectedRows.value.length > 0 && type == "batchCancel") {
    params = {
      dataset_id: datasetId.value.toString(),
      document_ids: selectedRows.value.map((item) =>
        item.document_id.toString()
      ),
    };
  }

  proxy.$modal.confirm("确定要停止解析文件吗？").then(() => {
    parseStop(params).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("已停止解析");
        getFileList();
      } else {
        proxy.$modal.msgError(res.msg || "停止解析失败");
      }
    });
  });
}

onMounted(() => {
  getFileList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  padding-bottom: 0;
}

.detail-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-breadcrumb {
  font-size: 14px;
}

.dataset-title-area {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.dataset-title-area h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.dataset-tip {
  display: flex;
  align-items: center;
  color: #e6a23c;
  font-size: 14px;
  gap: 5px;
}

.function-area {
  display: flex;
  justify-content: space-between;
  padding: 0 20px 15px;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.file-table-container {
  padding: 0 20px;
  flex: 1;
  overflow: auto;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.file-icon {
  margin-right: 6px;
  font-size: 18px;
}

.operation-btns {
  display: flex;
  justify-content: center;
  gap: 5px;
}

.pagination-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #ebeef5;
}

.page-info {
  color: #606266;
  font-size: 13px;
}

.total-count {
  color: #606266;
  font-size: 13px;
}

/* 上传组件样式 */
.file-upload-tabs {
  margin-bottom: 15px;
}

.upload-area {
  width: 100%;
  padding: 10px 0;
}

.custom-upload {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  border: 1px dashed #409eff;
  border-radius: 8px;
  background-color: #f9fbff;
  transition: border-color 0.3s;
}

.upload-content:hover {
  border-color: #79bbff;
}

.upload-icon-wrapper {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-box-icon {
  display: inline-block;
  width: 50px;
  height: 40px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='50' height='40' fill='%23409EFF'%3E%3Cpath d='M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z'/%3E%3C/svg%3E")
    no-repeat center;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.file-info {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding-left: 10px;
  font-size: 13px;
  color: #606266;
}

.file-info i {
  margin-right: 5px;
  color: #409eff;
}

.parse-option {
  margin-top: 15px;
  padding-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 10px;
}

/* 标签页样式优化 */
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

:deep(.el-tabs__active-bar) {
  height: 2px;
  background-color: #409eff;
}

:deep(.el-tabs__item) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: bold;
}

/* 上传组件内部样式覆盖 */
:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  padding: 0;
  border: none;
  background-color: transparent;
}

:deep(.el-upload-dragger:hover) {
  background-color: transparent;
}

.folder-upload-content {
  cursor: pointer;
}

.upload-folder-icon {
  display: inline-block;
  width: 50px;
  height: 45px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='50' height='45' fill='%23409EFF'%3E%3Cpath d='M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z'/%3E%3C/svg%3E")
    no-repeat center;
}

.folder-info {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.folder-name {
  display: flex;
  align-items: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.folder-name i {
  margin-right: 5px;
  color: #409eff;
}

.file-count {
  color: #606266;
  font-size: 13px;
}

.parse-status-wrapper {
  width: 100%;
}

.progress-status {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f9ff;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 12px;
  white-space: nowrap;
}

.status-text {
  display: flex;
  align-items: center;
  color: #409eff;
  margin-right: 4px;
}

.percentage-text {
  color: #409eff;
  font-weight: 500;
}

.pulse-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #409eff;
  margin-right: 4px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.2);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.success-status,
.failed-status,
.cancel-status,
.unstart-status {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.success-status {
  color: #67c23a;
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.failed-status {
  color: #f56c6c;
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.cancel-status {
  color: #d46b08;
  background-color: #fff7e6;
  border: 1px solid #d46b08;
}

.unstart-status {
  color: #08979c;
  background-color: #e6fffb;
  border: 1px solid #08979c;
}

/* 重命名对话框样式 */
:deep(.el-dialog__title) {
  font-weight: bold;
  font-size: 16px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-form-item__label-wrap) {
  display: flex;
  align-items: center;
}

:deep(.el-form-item__label-wrap .el-form-item__label::before) {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 文件夹内文件列表样式 */
.folder-files-list {
  margin-top: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.file-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item-icon {
  margin-right: 10px;
  color: #409eff;
}

.file-item-info {
  flex: 1;
  overflow: hidden;
}

.file-item-name {
  font-size: 14px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-item-size {
  font-size: 12px;
  color: #909399;
  margin-top: 3px;
}

.file-item-actions {
  margin-left: 10px;
}

/* 文件夹分组样式 */
.folder-groups {
  margin-top: 15px;
}

.folder-group {
  margin-bottom: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.folder-group-header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  font-size: 14px;
}

.folder-name {
  font-weight: 500;
  margin-left: 8px;
  margin-right: 5px;
  color: #303133;
}

.file-count {
  color: #909399;
  font-size: 12px;
}

.folder-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.files-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
}

.file-item-path {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 文件图标基本样式 */
.file-icon {
  margin-right: 6px;
  font-size: 18px;
}

/* 默认文档图标颜色 */
.file-icon {
  color: #409eff;
}

/* Excel文件图标颜色 */
.file-icon-xlsx,
.file-icon-xls,
.file-icon-csv {
  color: #10a37f !important;
}

/* Word文件图标颜色 */
.file-icon-doc,
.file-icon-docx,
.file-icon-odt {
  color: #4285f4 !important;
}

/* PDF文件图标颜色 */
.file-icon-pdf {
  color: #e64a19 !important;
}

/* 图片文件图标颜色 */
.file-icon-jpg,
.file-icon-jpeg,
.file-icon-png,
.file-icon-gif,
.file-icon-bmp,
.file-icon-webp,
.file-icon-svg {
  color: #9c27b0 !important;
}

/* 音频文件图标颜色 */
.file-icon-mp3,
.file-icon-wav,
.file-icon-ogg,
.file-icon-flac {
  color: #ff9800 !important;
}

/* 视频文件图标颜色 */
.file-icon-mp4,
.file-icon-webm,
.file-icon-mov,
.file-icon-avi,
.file-icon-mkv {
  color: #f44336 !important;
}

/* 压缩包文件图标颜色 */
.file-icon-zip,
.file-icon-rar,
.file-icon-7z,
.file-icon-tar,
.file-icon-gz {
  color: #795548 !important;
}

/* 代码文件图标颜色 */
.file-icon-js,
.file-icon-ts,
.file-icon-py,
.file-icon-java,
.file-icon-html,
.file-icon-css,
.file-icon-php,
.file-icon-go {
  color: #607d8b !important;
}

/* 文本文件图标颜色 */
.file-icon-txt,
.file-icon-md,
.file-icon-rtf {
  color: #9e9e9e !important;
}

/* 图片缩略图样式 */
.image-thumbnail {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  overflow: hidden;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.image-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.my-blue-icon {
  color: #17b26a;
}

.op-black-icon {
  color: #222 !important;
}

.file-svg-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  vertical-align: middle;
}

.stop-parse-btn {
  background: #fff !important;
  border: 1px solid #f56c6c !important;
  color: #f56c6c !important;
  transition: 0.2s;
}
.stop-parse-btn:hover {
  background: #f56c6c !important;
  color: #fff !important;
  border-color: #f56c6c !important;
}

.op-btn[disabled] {
  color: #bbb !important;
  cursor: not-allowed !important;
  background: #f5f5f5 !important;
  border-color: #eee !important;
}

/* 批量操作下拉菜单图标样式 */
.batch-menu-icon {
  margin-right: 8px;
  font-size: 18px;
  vertical-align: middle;
}
.batch-menu-icon.enable {
  color: #67c23a;
}
.batch-menu-icon.disable {
  color: #f56c6c;
}
.batch-menu-icon.parse {
  color: #4caf50;
}
.batch-menu-icon.cancel {
  color: #f56c6c;
}
.batch-menu-icon.delete {
  color: #909399;
}
/* 保证菜单项左对齐 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
}

/* 自定义tooltip样式 */
.custom-tooltip-content {
  padding: 8px;
  min-width: 300px;
  max-width: 600px;
  max-height: 400px; /* 添加最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
  white-space: pre-wrap;
  word-break: break-word;
}

/* 美化滚动条样式 */
.custom-tooltip-content::-webkit-scrollbar {
  width: 6px;
}

.custom-tooltip-content::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.custom-tooltip-content::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.tooltip-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 5px;
}

.tooltip-file-name {
  font-size: 13px;
  color: #606266;
  margin-bottom: 10px;
  word-break: break-all;
}

.tooltip-info-row {
  display: flex;
  font-size: 12px;
  margin-bottom: 5px;
}

.tooltip-label {
  color: #333;
  width: 70px;
  font-weight: bold;
  flex-shrink: 0;
}

.tooltip-value {
  color: #606266;
  flex: 1;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: monospace; /* 使用等宽字体，保持格式 */
  line-height: 1.5; /* 增加行高 */
}

/* 修改 tooltip 组件的样式 */
:deep(.el-tooltip__popper) {
  max-width: 600px !important;
  max-height: 400px !important;
}
</style> 
